package com.my.servlets;

import com.my.entity.User;
import com.my.user.service.IUserService;
import com.my.user.service.impl.UserServiceImpl;
import org.apache.commons.codec.binary.Base64;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.FileNameMap;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Locale;


public class DownloadServlet  extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String fileNmae = request.getParameter("fileName");
        //下载文件需要设置消息头
        response.addHeader("content-Type","application/octet-stream");

        //对于不同的浏览器，进行不同的处理
        //获取客户端user-agent信息
        String agent = request.getHeader("User-Agent");
        if(agent.toLowerCase().indexOf("firefox")!=-1){
            //Firefox中文乱码问题
            response.addHeader("content-Disposition","attachment;filename==?UTF-8?B?" + new String(Base64.encodeBase64(fileNmae.getBytes("UTF_8"))) + "?=");
        }else{
            //Edge中文乱码问题
            response.addHeader("content-Disposition","attachment;filename=" + URLEncoder.encode(fileNmae,"UTF-8"));
        }

        //Servlet通过文件的地址将文件转为输入流读到Servlet中
        InputStream in = getServletContext().getResourceAsStream("/rs/" + fileNmae);
        //通过输出流将刚才已经转为输入流的文件输出给用户
        ServletOutputStream out = response.getOutputStream();
        byte[] bs = new byte[10];
        int len = -1;
        while((len=in.read(bs))!=-1){
            out.write(bs,0,len);
        }
        out.close();
        in.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
